<?php
/**
 * User: xzq
 * Date: 2018/8/9
 * Time: 9:34
 */

namespace app\library\admin;
use app\admin\controller\Admin;
use app\library\model\Notice as NoticeModel;

class Notice extends Admin
{
    public function index(){
        $this->assign('tab_type', 3);
        if ($this->request->isAjax()) {
            $where = $data = [];
            $page = input('param.page/d', 1);
            $limit = input('param.limit/d', 15);
            $list = NoticeModel::where($where)->page($page)->limit($limit)->order('id desc')->select();
            $data['data'] = $list;
            $data['count'] = NoticeModel::where($where)->count('id');
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
        }
        return $this->fetch();
    }
    /**
     * 添加通知
     * @return mixed
     */
    public function add(){
        if ($this->request->isPost()) {
            $data = $this->request->post();
            // 验证
            $result = $this->validate($data, 'Notice.add');
            if($result !== true) {
                return $this->error($result);
            }
            unset($data['id']);
            $data['ctime'] = time();
            if (!NoticeModel::create($data)) {
                return $this->error('添加失败！');
            }
            return $this->success('添加成功。');
        }
        return $this->fetch('form');
    }
    /**
     * 删除通知
     * @return mixed
     */
    public function del(){
        $id = input('param.id/a');
        $model = new NoticeModel();
        if ($model->del($id)) {
            return $this->success('删除成功。');
        }
        return $this->error($model->getError());
    }
    /**
     * 修改通知
     * @return mixed
     */
    public function edit($id = 0){
        $row = NoticeModel::where('id', $id)->field('id,title,status,content')->find();
        if ($this->request->isPost()) {
            $data = $this->request->post();
            // 验证
            $result = $this->validate($data, 'Notice.edit');
            if($result !== true) {
                return $this->error($result);
            }
            if (!NoticeModel::update($data)) {
                return $this->error('修改失败！');
            }
            return $this->success('修改成功。');
        }
        $this->assign('data_info', $row);
        return $this->fetch('form');
    }
}